package com.example.demo.controller;

import com.example.demo.constant.Code;
import com.example.demo.pojo.Result;
import com.example.demo.pojo.dto.DeleteFileDTO;
import com.example.demo.pojo.properties.AliyunOssProperties;
import com.example.demo.utils.AliyunOssUtil;
import com.example.demo.utils.FileUtil;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/oss")
public class AliyunOssController {

    @Autowired
    private AliyunOssProperties aliyunOssProperties;

    @PostMapping("/upload")
    public Result uploadFile(MultipartFile file) throws IOException {
        String fileName = FileUtil.generateFileName(file);

        String url = AliyunOssUtil.uploadFile(aliyunOssProperties, file.getInputStream(), fileName);

        return new Result(Code.OSS_OK, url, "上传成功");
    }

    @DeleteMapping("/delete")
    public Result deleteFile(@RequestBody @Valid DeleteFileDTO deleteFileDTO) {
        String url = deleteFileDTO.getUrl();
        String objectName = url.substring(url.lastIndexOf("/") + 1);

        boolean result = AliyunOssUtil.deleteFile(aliyunOssProperties, objectName);

        int code = (result) ? Code.OSS_OK : Code.OSS_ERR;
        String message = (result) ? "删除文件成功" : "文件不存在";

        return new Result(code, null, message);
    }
}
